package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result pageDish(DishPageQueryDTO dishPageQueryDTO) {
        if(dishPageQueryDTO == null){
            return Result.error("查询分页失败...");
        }

        PageHelper.startPage(dishPageQueryDTO.getPage() , dishPageQueryDTO.getPageSize());

        Page<Dish> page = dishMapper.pageDish(dishPageQueryDTO);

        //！！多表联查
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish dish : page) {
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish, vo);

            vo.setCategoryName(categoryMapper.getByID(vo.getCategoryId()));
            dishVOList.add(vo);
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(dishVOList);

        return Result.success(pageResult);
    }

    /**
     * 新增菜品
     *  这是多表新增，一定要是用事务
     *  同时sql语句中，要使用这个属性：useGeneratedKeys="true" keyProperty="id"
     *  先行提交事务，返回下一张需要被修改的表，所需要的一些数据。
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public Result addFish(DishDTO dishDTO) {
        //1、边界条件
        if (dishDTO == null){
            Result.error("新增菜品失败");
        }


        //2、多表连接
        //2.1、插入菜品，并且获得菜品的id，
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insertDish(dish);
        Long dishID = dish.getId();

        //2.2、遍历该新增菜品的口味列表，并且将关联的dishID填充进去，然后写进第二张表
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishID);
            });
            dishFlavorMapper.insertDishFlavorList(flavors);//后绪步骤实现
        }
        return Result.success();
    }

    /**
     * 批量删除
     *  多表连接，需要查询目前表是否被别的表所关联
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteDish(List<Long> ids) {
        //边界判断
        if(ids == null || ids.size() == 0){
            Result.error("删除列表数据异常，删除失败...");
        }

        //1.查询当前菜品是否存在
        //  -如果不存在，就返回失败。
        //  -如果存在，就查询起售状态，如果是则不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getByDishId(id);
            if(dish == null){
                return Result.error("菜品不存在，删除失败...");
            }else{
                if(dish.getStatus() == StatusConstant.ENABLE){
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }
            }
        }


        //2.查询当前菜品是否关联套餐，如果关联则不能删除，并且返回值
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealDishIds != null && setmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.都没问题了，就可以开始多表删除了，两张表的相关数据都要一起删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);
        return Result.success();
    }

    /**
     * 改变菜品状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result changeDishStatus(Integer status, Long id) {
        //边界判断
        if(status == null || id == null){
            return Result.error("信息错误");
        }
        //补全信息
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);

        //调用mapper
        dishMapper.changeDishStatus(dish);

        //返回值
        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
}
